/*
 * 이 스크립트는 String 타입에 serialize() 메서드를 추가합니다. 
 * 예를들어 "뷁".serialize() 는 "ㅂㅜㅔㄹㄱ"을 리턴합니다.
 */

var KLT ={
	CHOSUNG : "ㄱㄲㄴㄷㄸㄹㅁㅂㅃㅅㅆㅇㅈㅉㅊㅋㅌㅍㅎ",
	JUNGSUNG : "ㅏㅐㅑㅒㅓㅔㅕㅖㅗㅘㅙㅚㅛㅜㅝㅞㅟㅠㅡㅢㅣ",
	JONGSUNG :"ㄱㄲㄳㄴㄵㄶㄷㄹㄺㄻㄼㄽㄾㄿㅀㅁㅂㅄㅅㅆㅇㅈㅊㅋㅌㅍㅎ",
	CHOSUNG_INTERVAL : '까'.charCodeAt(0) - '가'.charCodeAt(0),
	JUNGSUNG_INTERVAL : '애'.charCodeAt(0) - '아'.charCodeAt(0),
	DECOMP_MAP : new Array(),
	OFFSET_OF_GA : '가'.charCodeAt(0)
};

KLT.DECOMP_MAP['ㄳ'] = "ㄱㅅ";
KLT.DECOMP_MAP['ㄵ'] = "ㄴㅈ";
KLT.DECOMP_MAP['ㄶ'] = "ㄴㅎ";
KLT.DECOMP_MAP['ㄺ'] = "ㄹㄱ";
KLT.DECOMP_MAP['ㄻ'] = "ㄹㅁ";
KLT.DECOMP_MAP['ㄼ'] = "ㄹㅂ";
KLT.DECOMP_MAP['ㄽ'] = "ㄹㅅ";
KLT.DECOMP_MAP['ㄾ'] = "ㄹㅌ";
KLT.DECOMP_MAP['ㄿ'] = "ㄹㅍ";
KLT.DECOMP_MAP['ㅄ'] = "ㅂㅅ";
KLT.DECOMP_MAP['ㅘ'] = "ㅗㅏ";
KLT.DECOMP_MAP['ㅙ'] = "ㅗㅐ";
KLT.DECOMP_MAP['ㅚ'] = "ㅗㅣ";
KLT.DECOMP_MAP['ㅝ'] = "ㅜㅓ";
KLT.DECOMP_MAP['ㅞ'] = "ㅜㅔ";
KLT.DECOMP_MAP['ㅟ'] = "ㅜㅣ";
KLT.DECOMP_MAP['ㅢ'] = "ㅡㅣ";


KLT.isCompletedKoreanCharacterCode = function (cc){
	return '가'.charCodeAt(0) <= cc && cc <= '힣'.charCodeAt(0);  
};

KLT.getChosung = function(cc){
	var index = (cc - this.OFFSET_OF_GA) / this.CHOSUNG_INTERVAL;
	return this.CHOSUNG.charAt(index);
}

KLT.getJungsung = function(cc) {
	var index = (cc - this.OFFSET_OF_GA) % this.CHOSUNG_INTERVAL / this.JUNGSUNG_INTERVAL;
	return this.JUNGSUNG.charAt(index);
}

KLT.getJongsung = function(cc) {
	var index = (cc - this.OFFSET_OF_GA) % this.JUNGSUNG_INTERVAL - 1;
	if (index == -1) {
		return undefined;
	} else {
		return this.JONGSUNG.charAt(index);
	}
}

KLT.serialize = function (str){
	var length = str.length;
	var result = "";
	
	for(var i=0; i<length; i++){
		var c = str.charAt(i);
		var cc = str.charCodeAt(i);
		
		if(!this.isCompletedKoreanCharacterCode(cc)){
			result += c;
			continue;
		}
		
		var chosung = this.getChosung(cc);
		var jungsung = this.getJungsung(cc);
		var jongsung = this.getJongsung(cc);
		
		if(this.DECOMP_MAP[chosung]){
			result += this.DECOMP_MAP[chosung];
		}else{
			result += chosung;
		}
		
		if(this.DECOMP_MAP[jungsung]){
			result += this.DECOMP_MAP[jungsung];
		}else{
			result += jungsung;
		}
		
		if(jongsung){
			if(this.DECOMP_MAP[jongsung]){
				result += this.DECOMP_MAP[jongsung];
			}else{
				result += jongsung;
			}
		}
	}
	
	return result;
};

/**
 * "꿀토끼" -> "ㄲㅜㄹㅌㅗㄲㅣ" 처럼, 직렬화 하여 리턴합니다.
 */
String.prototype.serialize = function(){
	return KLT.serialize(this);
}